var api = require('./api')

function loading(e, c) {
  wx.showLoading({mask: !0, title: e || "加载中...", success: c})
}

function alert(e, c, t, ic) {
  wx.showToast({title: e || "操作成功", icon: ic || "success", duration: t || 2e3, success: c})
}

function hideloading() {
  var e = setTimeout(function () {
    wx.hideLoading()
  }, 500)
}

function alertModal(e, ck) {
  wx.showModal({title: "提示", content: e || '手机号码格式有误!', success: ck, showCancel: false});
}

function parseJSON(e) {
  try {
    return JSON.parse(e)
  } catch (t) {
    return undefined
  }
}

function get(url, p, ok, f) {
  var en = encodeURIComponent;
  p = p == 0 ? {} : p
  console.log(">>>get url=" + url)
  // p.ts = new Date().getTime()
  for (var n in p) {
    url = url.indexOf("?") > 0 ? url + "&" + n + "=" + p[n] : url + "?" + n + "=" + p[n];
  }
  wx.request({
    url: url,
    method: 'GET',
    header: {
      'Accept': 'application/json'
    },
    success: function (e) {
      console.log(e)
      e.data && ok(e.data)
    }
  });
}
function showmenu() {
  wx.showShareMenu({
    withShareTicket: true,
    menus: ['shareAppMessage', 'shareTimeline']
  })
}
function post(url, p, ok, f) {
  console.log(">>>httpPost url=" + url)
  wx.request({
    url: url,
    method: 'POST',
    header: {
      'content-type': 'application/x-www-form-urlencoded'
    },
    data: p,
    success: function (e) {
      if (e.data.token) wx.setStorageSync('token', e.data.token)
      hideloading();
      e.data && ok && ok(e.data)
    },
    fail: !!f ? f : 0
  });
}

function checkPhone(phone, showTip) {
  if (!(/^1[3456789]\d{9}$/.test(phone))) {
    if (showTip) {
      wx.showModal({
        title: "提示",
        content: '手机号码格式有误!',
        showCancel: false
      });
    }
    return false;
  } else {
    return true;
  }
}

function isNull(e) {
  return e == undefined || e == "undefined" || e == null || e == ""
}

function isAuth() {
  return !isNull(wx.getStorageSync('uid'))
}

function uid() {
  return wx.getStorageSync('uid')
}

function touxian() {
  return wx.getStorageSync('avatarUrl')
}

function nichen() {
  return wx.getStorageSync('nickName')
}

function wxlogin(e, ck) {
  console.log("==========wxlogin2")
  console.log(e)
  loading();
  var u = e.userInfo, ud = wx.getStorageSync('ud'),
    p = {encryptedData: e.encryptedData, iv: e.iv, ori: gcache('ori') || "", hxscene: gcache('hxscene') || ""}
  if (ud) p.ud = ud
  wx.setStorageSync('avatarUrl', u.avatarUrl);
  wx.setStorageSync('nickName', u.nickName);
  wx.setStorageSync('userInfo', u);
  wx.login({
    success: function (r) {
      hideloading()
      console.log(r)
      p.code = r.code;
      post(api.userLogin, p, function (e) {
        console.log(e)
        e.code != 0 ? console.log('login fail') : ck && ck(e)
      });
    },
    fail: function () {
      hideloading()
      log('wxlogin fail')
    }
  })
  function gcache(k) {
    return wx.getStorageSync(k)
  }
  function ssid() {
    return gcache('ssid')||''
  }
  function sessionCheck() {
    wx.checkSession({
      success: function () {
        // session_key 未过期，并且在本生命周期一直有效
        get(api.sessionStay,{})
      },
      fail: function () {
        // session_key 已经失效，需要重新执行登录流程
        get(api.sessionClear,{})
      }
    })
  }
  function getDistance(lat1, lng1, lat2, lng2) {
    
    lat1 = lat1 || 0;
    lng1 = lng1 || 0;
    lat2 = lat2 || 0;
    lng2 = lng2 || 0;
    
    var rad1 = lat1 * Math.PI / 180.0;
    var rad2 = lat2 * Math.PI / 180.0;
    var a = rad1 - rad2;
    var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
    var r = 6378137;
    return (r * 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) * Math.cos(rad2) * Math.pow(Math.sin(b / 2), 2)))).toFixed(0)
  }
}

module.exports = {
  get: get,
  checkPhone: checkPhone,
  alert: alert,
  alertModal: alertModal,
  showmenu: showmenu,
  parseJSON: parseJSON,
  isNull: isNull,
  isAuth: isAuth,
  loading: loading,
  hideloading: hideloading,
  touxian: touxian,
  nichen: nichen,
  wxlogin: wxlogin,
  uid: uid,
  post: post
}